import React from 'react';
import {Spin, Card, Button, Row, Col, Table, Form, Popconfirm} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, TABLE, FIXED_COLUMN_WIDTH} from '../constants';
import {getDetail, updateApplyReport} from './api';
import {injectIntl} from './intl';
import TextInput from 'Shared/components/TextInput';
import WrappedSelect from '../common/WrappedSelect';
import {uuid} from './utils';
import styles from './style.css';
import Return from '../common/Return';
import {newOrUpdateOrderValidator} from './validator';
const FormItem = Form.Item;

class AddPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        data: {},
        details: [],
    }
    componentDidMount() {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                        details: res.data.details,
                    });
                else
                    this.setState({loading: false});
            });
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const data = this.state.data;
        const details = this.state.details;
        const isValid = newOrUpdateOrderValidator(data, details);
        if(!isValid) {
            this.setState({
                isValidate: true
            });
            return;
        }
        const condition = {
            brandId: data.brandId,
            code: data.code,
            name: data.name,
            shortName: data.shortName,
            rowVersion: data.rowVersion,
            details: details.map(v => ({
                contact: v.contact,
                contactNumber: v.contactNumber,
                fax: v.fax,
                email: v.email,
                remark: v.remark,
            }))
        };
        this.setState({loading: true});
        updateApplyReport(this.props.id, condition).then(res => {
            if(res.ok)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }

    onDeleteAll = () => {
        this.setState({
            details: [],
            hasOperat: true
        });
    }
    onDeleteDetail = e => {
        const id = e.target.dataset.id;
        const details = this.state.details.filter(p => p.id !== id);
        this.setState({
            details,
            hasOperat: true
        });
    }
    onClickAddDetailBtn = () => {
        const details = this.state.details;
        this.setState({
            details: [
                ...details,
                {
                    id: uuid()
                }
            ]
        });
    };
    onChangeAll = (value, id, e) => {
        const details = this.state.details || [];
        const name = e.target.name;
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    [name]: value
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, details, isValidate, loading} = this.state;
        const {brands} = this.props.initEnumData;
        const columns = [{
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'addPanel.column.contact',
                defaultMessage: '货代联系人'
            })}</span>,
            dataIndex: 'contact',
            render: (text, record) => {
                const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <TextInput
                            name="contact"
                            id={record.id}
                            value={text} onBlur={this.onChangeAll}/>
                    </FormItem>
                );
            }
        }, {
            title: <span className="ant-form-item-required">{formatMessage({
                id: 'addPanel.column.contactNumber',
                defaultMessage: '货代电话'
            })}</span>,
            dataIndex: 'contactNumber',
            render: (text, record) => {
                const validate = !text && isValidate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <TextInput
                            id={record.id}
                            name="contactNumber"
                            value={text} onBlur={this.onChangeAll}/>
                    </FormItem>
                );
            }
        }, {
            title: formatMessage({
                id: 'addPanel.column.fax',
                defaultMessage: '货代传真'
            }),
            dataIndex: 'fax',
            render: (text, record) => (
                <FormItem>
                    <TextInput
                        id={record.id}
                        name="fax"
                        value={text} onBlur={this.onChangeAll}/>
                </FormItem>
            )
        }, {
            title: formatMessage({
                id: 'addPanel.column.email',
                defaultMessage: '货代邮件'
            }),
            dataIndex: 'email',
            render: (text, record) => (
                <FormItem>
                    <TextInput
                        id={record.id}
                        name="email"
                        value={text} onBlur={this.onChangeAll}/>
                </FormItem>
            )
        }, {
            title: formatMessage({
                id: 'addPanel.column.remark',
                defaultMessage: '备注'
            }),
            dataIndex: 'remark',
            render: (text, record) => (
                <FormItem>
                    <TextInput
                        id={record.id}
                        name="remark"
                        value={text} onBlur={this.onChangeAll}/>
                </FormItem>
            )
        }, {
            title: details.length > 0
                ? (
                    <Popconfirm placement="topRight" title={formatMessage({
                        id: 'addPanel.validation.isDelete',
                        defaultMessage: '是否确认全部删除？'
                    })} onConfirm={this.onDeleteAll} >
                        <a>{formatMessage({
                            id: 'addPanel.validation.clear',
                            defaultMessage: '清空'
                        })}</a>
                    </Popconfirm>
                )
                : null,
            dataIndex: 'id',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: text => <a data-id={text} onClick={this.onDeleteDetail}>{formatMessage({
                id: 'addPanel.validation.delete',
                defaultMessage: '删除'
            })}</a>
        }];
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'addPanel.column.common',
                        defaultMessage: '货代信息'
                    })}>
                        <Form>
                            <Row>
                                <Row>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={formatMessage({
                                                id: 'addPanel.form.brands',
                                                defaultMessage: '品牌'
                                            })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.brandId ? 'error' : null} required>
                                            <WrappedSelect
                                                allowClear
                                                name="brandId"
                                                options={brands}
                                                value={data.brandId}
                                                onChange={this.onChange}/>
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'addPanel.form.code',
                                            defaultMessage: '货代编码'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={isValidate && !data.code ? 'error' : null} required>
                                            <TextInput
                                                name="code"
                                                value={data.code}
                                                onBlur={this.onChange}/>
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'addPanel.form.name',
                                            defaultMessage: '货代名称'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={isValidate && !data.name ? 'error' : null} required>
                                            <TextInput
                                                name="name"
                                                value={data.name}
                                                onBlur={this.onChange}/>
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem className={styles.multiLabel} label={formatMessage({
                                            id: 'addPanel.form.shortName',
                                            defaultMessage: '货代简称'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={isValidate && !data.shortName ? 'error' : null} required>
                                            <TextInput
                                                name="shortName"
                                                value={data.shortName}
                                                onBlur={this.onChange}/>
                                        </FormItem>
                                    </Col>
                                </Row>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'addPanel.operation.detail',
                            defaultMessage: '货代信息清单'
                        })}>
                        <Button
                            type="dashed"
                            icon="plus"
                            block
                            className={styles.plusBtn}
                            onClick={this.onClickAddDetailBtn}>
                            {formatMessage({
                                id: 'addPanel.couponInfo.operation.new',
                                defaultMessage: '新增'
                            })}
                        </Button>
                        <Table
                            className="white-space-nowrap"
                            columns={columns}
                            rowKey="id"
                            pagination={false}
                            dataSource={details}
                            {...TABLE} />
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            loading={loading}>
                            {formatMessage({
                                id: 'addPanel.operation.onSubmit',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

AddPanel.propTypes = {
    initEnumData: PropTypes.object.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    tableSearch
} from './actions';
import {createSelector} from 'reselect';
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'init']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: item.name,
            value: item.id
        })) : [];
        return {
            brands
        };
    }
);
const mapStateToProps = state => ({
    initEnumData: getinitEnumData(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(AddPanel));
